//
//  MainViewController.swift
//  WeiBo09
//
//  Created by 裘明 on 15/8/31.
//  Copyright © 2015年 qm. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加子控制器
        addChildViewControllers()
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        /// 设置撰写按钮
        setupcomposedButten()
        
    }
    
    /// 设置撰写按钮
    private func setupcomposedButten() {
        
        let count = childViewControllers.count
        
        // 计算每个按钮的宽度
        let w = tabBar.bounds.width / CGFloat(count)
        
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        composedButten.frame = CGRectOffset(rect, w * 2, 0)
    }
    
    // 为UITabBar添加子控制器
    private func addChildViewControllers() {
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    // 设置子控制器的属性
    private func addChildViewController(vc: UIViewController, title:String, imageName:String) {
        
        // 设置标题 navigationItem + tabBarItem
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
        
    }
    
    // 撰写按钮的懒加载
    private lazy var composedButten: UIButton = {
        
        let btn = UIButton()
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 撰写按钮添加点击事件
        btn.addTarget(self, action: "clickComposeBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        self.tabBar.addSubview(btn)
        
        return btn
    }()
    
    
    /// 撰写按钮
    @objc private func clickComposeBtn() {
        
        let vc: UIViewController
        if UserAccountViewModel.sharedUserAccount.userLogin  {
            vc = ComposeViewController()
        } else  {
            vc = OAuthViewController()
        }
        
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
    }
    
}
